package cn.xd.base.controller.general;


import cn.xd.base.application.assembler.GlobalAppUserSimplifyDTOAssembler;
import cn.xd.base.application.dto.GlobalAppUserSimplifyDTO;
import cn.xd.base.application.dto.query.GetGlobalAppUserByPhoneQuery;
import cn.xd.base.application.service.command.GlobalAppUserAppService;
import cn.xd.base.application.service.query.GlobalAppUserQueryAppService;
import cn.xd.base.domain.bean.command.ChangePasswordCommand;
import cn.xd.base.domain.entity.GlobalAppUser;
import cn.xd.base.persistence.dos.GlobalAppUserConverter;
import cn.xd.common.constant.AuthConstant;
import cn.xd.common.domain.auth.CurrentUser;
import cn.xd.common.response.ResponseResult;
import cn.xd.web.utils.SecurityUtils;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局用户管理
 *
 * @author chenyh
 * @since 2023-09-08
 */
@RestController
@RequestMapping("/member/globalAppUser")
public class GlobalAppUserController {

    @Resource
    private GlobalAppUserAppService globalAppUserAppService;

    @Resource
    private GlobalAppUserQueryAppService globalAppUserQueryAppService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 修改密码
     */
    @PostMapping("changePassword")
    public ResponseResult<?> changePassword(@RequestBody @Validated ChangePasswordCommand command) {
        globalAppUserAppService.changePassword(command);
        return ResponseResult.success();
    }

    @PostMapping("getByPhone")
    public ResponseResult<GlobalAppUserSimplifyDTO> getByPhone(@RequestBody @Validated GetGlobalAppUserByPhoneQuery query) {
        GlobalAppUser globalAppUser = globalAppUserQueryAppService.getGeneralUserByPhone(query.getPhone()).get();
        return ResponseResult.success(GlobalAppUserSimplifyDTOAssembler.INSTANCE.fromData(GlobalAppUserConverter.INSTANCE.toData(globalAppUser)));
    }

    /**
     * 查询当前用户信息（redis）
     *
     * @return
     */
    @PostMapping("/getInfo")
    public ResponseResult<Map<String, Object>> getInfo() {
        CurrentUser user = SecurityUtils.getUser();
        String jwtKey = String.format(AuthConstant.AUTH_USER_KEY_FORMAT, user.getAppUserType().getCode(), user.getUserSource().getCode(), user.getId(), "0");
        String key = (String) redisTemplate.opsForValue().get(jwtKey);
        String userInfoKey = String.format(AuthConstant.AUTH_USER_INFO_FORMAT, key);
        Object userInfo = redisTemplate.opsForValue().get(userInfoKey);
        Map<String, Object> res = new HashMap<>();
        res.put("info", userInfo);
        return ResponseResult.success(res);
    }

}
